package com.offcn.bigdata.common.db;

import com.offcn.bigdata.common.CommonUtil;
import com.offcn.bigdata.common.conf.Constants;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;
import java.util.Properties;

/**
 * 自己搞的数据库连接池
 */
public class ConnectionPool {

    private ConnectionPool(){}

    //存放Connection的容器 lian表
    private static LinkedList<Connection> pool = new LinkedList<>();
    static {

        Properties properties = new Properties();
        try {
            properties.load(ConnectionPool.class.getClassLoader().getResourceAsStream("jdbc.properties"));

            String url = properties.getProperty(Constants.JDBC_URL);
            String driver = properties.getProperty(Constants.JDBC_DRIVER);
            String username = properties.getProperty(Constants.JDBC_USERNAME);
            String password = properties.getProperty(Constants.JDBC_PASSWORD);

            Class.forName(driver);
            for(int i = 0; i < 5; i++) {
                pool.push(DriverManager.getConnection(url, username, password));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        while (pool.isEmpty()) {
            CommonUtil.sleep(1000);
        }
        return pool.poll();
    }


    public static void release(Connection connection) {
        pool.push(connection);
    }
}
